package com.weixing.mall.provider.support.excel;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author jzy
 * @date 2020/6/17
 */
public class EasyExcelUtil {
    /**
     * Excel文件导出
     * @param response
     * @param pojoClass：导出的实体类
     * @param data：要导出的数据
     * @param fileName：Excel标题名称
     * @throws Exception
     */
    public static void writeExcel(HttpServletResponse response, Class<?> pojoClass,List<?> data,String fileName) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        if(StrUtil.isEmpty(fileName)){
            fileName = DateUtil.now();
        }
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName2 = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName2 + ".xlsx");
        EasyExcel.write(response.getOutputStream(), pojoClass).sheet(fileName).doWrite(data);
    }
}
